﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Script.Serialization;
using System.Web.Security;

using MvcSystemsCommander.Extensions.Security;
using MvcSystemsCommander.Models.Service;

namespace MvcSystemsCommander
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            NavigationRouteConfig.RegisterRoutes(RouteTable.Routes);
            
        }

        protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
        {
            HttpCookie cookie = Request.Cookies[FormsAuthentication.FormsCookieName];

            // First we check for an existing cookie, and if there is one, we prefer that.
            // Then, we check for a match of the Windows auth user and one in DB

            if (cookie != null)
            {
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                MSCPrincipalSerializeModel serialModel = serializer.Deserialize<MSCPrincipalSerializeModel>(ticket.UserData);

                MSCPrincipal principal = new MSCPrincipal(serialModel.Username, MSCIdentityAuthenticationType.ApplicationAuthentication);
                HttpContext.Current.User = principal;
            }
            else
            {
                AuthenticationService s = new AuthenticationService();

                string uName = s.UsernameForWindowsAuthIdentity(Request.LogonUserIdentity.Name);

                if (uName != null)
                {
                    MSCPrincipal principal = new MSCPrincipal(uName, MSCIdentityAuthenticationType.WindowsAuthentication);
                    HttpContext.Current.User = principal;
                }
            }
        }

    }

}